package com.fieldchain.ex.fa100.ui.access;

import android.content.Intent;
import android.support.design.widget.TabLayout;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.RadioGroup;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.fieldchain.ex.fa100.R;
import com.fieldchain.ex.fa100.access.Constant;
import com.fieldchain.ex.fa100.base.MyBaseFragment;
import com.fieldchain.ex.fa100.bean.MarketBean;
import com.fieldchain.ex.fa100.bean.event.BaseEvent;
import com.fieldchain.ex.fa100.custom.view.MySortRadio;
import com.fieldchain.ex.fa100.inter.IntegerCallBack;
import com.fieldchain.ex.fa100.inter.StringCallBack;
import com.fieldchain.ex.fa100.ui.market.adapter.MarketAdapter;
import com.fieldchain.ex.fa100.ui.market.adapter.MarketCompare;
import com.fieldchain.ex.fa100.ui.personal.activity.PersonalCanterActivity;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;

import com.fieldchain.ex.fa100.utils.net.access.HttpRequest;
import com.fieldchain.ex.fa100.utils.net.access.WebSocketRequet;
import com.fieldchain.ex.fa100.utils.net.modle.StringListRequest;

import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

/**
 * Created by biyunlong
 * Email: 1225198434@qq.com
 * Data:  2018/9/16
 */
public class MarketFragment extends MyBaseFragment {
    private ImageView ivPersonal;
    private ImageView tvTitle;
    private TabLayout tablelayout;
    private MySortRadio rb0;
    private MySortRadio rb1;
    private MySortRadio rb2;
    private MySortRadio rb3;
    private RecyclerView rv;
    private RelativeLayout reaEmpty;
    private TextView tvEmpty;
    private RadioGroup rg;
    private List<MarketBean> mList = new ArrayList<>();
    private List<String> coinList = new ArrayList<>();
    private MarketAdapter adapter;
    private WebSocketRequet webSocket;
    private String market = "";
    private String tabTags = "";

    private int sortIndex = -1,
            sortType = -1;
    private String[] strMethod = {"getMarket", "getVolume", "getRecentQuotation", "getChange"};
    private boolean isFirst = true;

    @Override
    protected void findView() {
        ivPersonal = view.findViewById(R.id.iv_personal);
        tvTitle = view.findViewById(R.id.tv_title);
        tablelayout = view.findViewById(R.id.tablelayout);
        rb0 = view.findViewById(R.id.rb0);
        rb1 = view.findViewById(R.id.rb1);
        rb2 = view.findViewById(R.id.rb2);
        rb3 = view.findViewById(R.id.rb3);
        rv = view.findViewById(R.id.rv);
        reaEmpty = view.findViewById(R.id.rea_empty);
        tvEmpty = view.findViewById(R.id.tv_empty);
        rg = view.findViewById(R.id.rg);
    }

    @Override
    protected void setValue() {
        setRadioTags(rb0, 0);
        setRadioTags(rb1, 1);
        setRadioTags(rb2, 2);
        setRadioTags(rb3, 3);

        tvEmpty.setText("暂无数据");
        initTable();
        initRv();

        ivPersonal.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                startActivity(new Intent(mContext, PersonalCanterActivity.class));
            }
        });
        getData();
    }

    private void getData() {
        HttpRequest.getInstance().getRequest(Constant.mk_tradcoin, new StringListRequest() {
            @Override
            public void onSucess(List<String> list, int code, String msg) {
                if (code == 200) {
                    coinList.clear();
                    coinList.addAll(list);
                    tablelayout.removeAllTabs();
                    tablelayout.addTab(tablelayout.newTab().setText("自选"));
                    for (int i = 0; i < list.size(); i++) {
                        String tab = list.get(i).toUpperCase();
                        tablelayout.addTab(tablelayout.newTab().setText(tab));
                        if (tab.equals(tabTags.toUpperCase())) {
                            tablelayout.getTabAt(i + 1).select();
                        }
                    }

                    if (tabTags.length() == 0 && coinList.size() > 0) {
                        tablelayout.getTabAt(1).select();
                    }

                    if (list == null || list.size() == 0) {
                        reaEmpty.setVisibility(View.VISIBLE);
                    }
                }
            }

            @Override
            public void onFaild(Exception e) {

            }
        });
    }

    public void initTable() {
        tablelayout.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
            @Override
            public void onTabSelected(TabLayout.Tab tab) {
                String tag = tab.getText().toString().toLowerCase();
                if (isFirst && tag.equals("自选")) {
                    return;
                }
                tabTags = tag;
                isFirst = false;
                adapter.clear();
                rg.clearCheck();
                startWebSocket(tag);
            }

            @Override
            public void onTabUnselected(TabLayout.Tab tab) {

            }

            @Override
            public void onTabReselected(TabLayout.Tab tab) {

            }
        });
    }

    public void initRv() {
        rv.setLayoutManager(new LinearLayoutManager(mContext));
        adapter = new MarketAdapter(mContext);
        rv.setAdapter(adapter);
    }

    @Override
    public int getLayout() {
        return R.layout.fragment_market;
    }

    public void setRadioTags(MySortRadio radio, final int index) {
        radio.setDrawable(R.drawable.icon_sort0, R.drawable.icon_sort1, R.drawable.icon_sort2);
        radio.setListener(new IntegerCallBack() {
            @Override
            public void index(int type) {
                Log.e("type_mk:", "index: " + index + "  type:" + type);
                sortIndex = index;
                sortType = type - 1;
                if (type > 0) {
                    adapter.sort(index, type - 1);
                }

            }
        });
    }


    @Override
    public void onResume() {
        super.onResume();
        if (tabTags.length() > 0) {
            startWebSocket(tabTags);
        }
    }

    @Override
    public void onPause() {
        super.onPause();
        if (webSocket != null) {
            webSocket.close();
        }
        isFirst = true;
    }

    public void startWebSocket(String coin) {
        String msg = coin;
        if (coin.equals("自选")) {
            msg = "optional";
        }
        HashMap map = new HashMap();
        map.put("event", "marketList");
        map.put("market", msg);
        map.put("type", "phone");
        String send = new Gson().toJson(map);
        if (null == webSocket) {
            webSocket = new WebSocketRequet();
        }
        webSocket.start(Constant.webSocket, send, new StringCallBack() {
            @Override
            public void message(String msg) {
                Log.e("socket1111", msg);
                checkData(msg);
            }
        });
    }

    public void checkData(String str) {
        List<MarketBean> list = new ArrayList<>();
        if (!str.startsWith("500")) {
            list = new Gson().fromJson(str, new TypeToken<List<MarketBean>>() {
            }.getType());
            if (list != null) {
                if (sortType >= 0 && list.size() > 0) {
                    Collections.sort(list, new MarketCompare(strMethod[sortIndex], sortType));
                }
            }
        }
        adapter.setData(list);

        if (list.size() > 0) {
            reaEmpty.setVisibility(View.GONE);
        } else {
            reaEmpty.setVisibility(View.VISIBLE);
        }
    }
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void MessageEvent(BaseEvent event) {
        if(event.getType()==5000){
            isFirst=false;
        }
    }

}
